package com.clsclassloder;

import java.io.*;
import java.nio.file.Files;

public class MyClassLoader extends ClassLoader {

    private final String classDir;

    public MyClassLoader(String classDir) {
        this.classDir = classDir;
    }

    // 维持双亲委派机制
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String[] nameSeg = name.split("\\.");
        String clsFileName = nameSeg[nameSeg.length - 1] + ".class";
        File file = new File(classDir, clsFileName);

        try (InputStream is = Files.newInputStream(file.toPath())) {
            int available = is.available();
            byte[] buffer = new byte[available];
            int read = is.read(buffer);
            
            return defineClass(name, buffer, 0, available);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        return super.findClass(name);
    }
}
